﻿using cn.school.Models.Entities;
using cn.school.Models.Exceptions;
using cn.school.Models.Req;
using cn.school.Models.Res;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;

namespace cn.school.api.v1;

public class StudentManage : IStudentManage
{
    private readonly ManageContext _context;
    private readonly ILogger<StudentManage> _logger;

    public StudentManage(ManageContext context, ILogger<StudentManage> logger)
    {
        _context = context;
        _logger = logger;
    }

    public Student AddOne(Student student)
    {
        if (_context.Students is null)
            throw new LogicException($"传入了一个空的学生数据", 400);
        student.IsDeleted = 0; // false - 表示未被删除
        student.CreateTime = DateTime.Now;
        student.Creator = "root";
        student.CreatorId = 0;
        _context.Students.Add(student);
        _context.SaveChanges();
        _logger.LogInformation("添加了一名新的学生");
        return student;
    }

    public Student GetById(long id)
    {
        var stu = _context.Students.AsNoTracking().SingleOrDefault(s => s.Id == id && s.IsDeleted == 0);
        return stu is null ? throw new LogicException($"{id} 对应的学生数据未找到", 404) : stu;
    }

    public WithPage<Student> List(StudentListReq req)
    {
        if (req is null)
            throw new LogicException($"查询条件为空", 400);
        var sql = _context.Students.Where(s => (req.Email == null || s.Email.Contains(req.Email))
        && (req.Name == null || s.Name.Contains(req.Name)))
            .OrderBy(s => s.Id)
            .Skip(req.Count())
            .Take(req.Size)
            .AsNoTracking();
        return new WithPage<Student>
        {
            List = sql.ToList(),
            Total = sql.Count()
        };
    }
}
